package com.self.av;

import android.content.Context;

import androidx.media3.datasource.DefaultDataSource;
import androidx.media3.datasource.cache.CacheDataSource;
import androidx.media3.datasource.cache.LeastRecentlyUsedCacheEvictor;
import androidx.media3.datasource.cache.SimpleCache;

public class CacheManager {
    private static SimpleCache simpleCache;
    private static CacheDataSource.Factory cacheDataSourceFactory;

    private CacheManager() {}

    public static synchronized SimpleCache getSimpleCache(Context context) {
        if (simpleCache == null) {
            LeastRecentlyUsedCacheEvictor leastRecentlyUsedCacheEvictor = new LeastRecentlyUsedCacheEvictor(100 * 1024 * 1024);
            simpleCache = new SimpleCache(context.getCacheDir(), leastRecentlyUsedCacheEvictor);
        }
        return simpleCache;
    }

    public static synchronized CacheDataSource.Factory getCacheDataSourceFactory(Context context) {
        if (cacheDataSourceFactory == null) {
            SimpleCache cache = getSimpleCache(context);
            DefaultDataSource.Factory defaultDataSourceFactory = new DefaultDataSource.Factory(context);
            cacheDataSourceFactory = new CacheDataSource.Factory()
                    .setCache(cache)
                    .setUpstreamDataSourceFactory(defaultDataSourceFactory)
                    .setFlags(CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR);
        }
        return cacheDataSourceFactory;
    }
}